package kr.hkit.androidcomplete02.ch19;

import kr.hyunist.androidcomplete01.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class LooperEx extends Activity {
	TextView mMainTv;
	TextView mBackTv;
	EditText mEdit;
	int mMainValue = 0;
	CalcThread thread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_loopertest);
		
		mMainTv = (TextView) findViewById(R.id.ch19_looper_mainvalue);
		mBackTv = (TextView) findViewById(R.id.ch19_looper_backvalue);
		mEdit= (EditText) findViewById(R.id.ch19_looper_number);
		
		thread = new CalcThread(mMainHandler);
		thread.setDaemon(true);
		thread.start();
	}
	
	public void mOnClick(View v){
		Message msg = null;
		
		switch(v.getId()){
		case R.id.ch19_looper_increase:
			mMainValue++;
			mMainTv.setText("MainValue : " + mMainValue);
			break;
		case R.id.ch19_looper_square:
			msg = Message.obtain(thread.mBackHandler,0 ,Integer.parseInt(mEdit.getText().toString()),0);
			thread.mBackHandler.sendMessage(msg);
			break;
		case R.id.ch19_looper_root:
			msg = Message.obtain(thread.mBackHandler,1 ,Integer.parseInt(mEdit.getText().toString()),0);
			thread.mBackHandler.sendMessage(msg);
			break;
		}
		
	}
	
	Handler mMainHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0:
				mBackTv.setText("Square Result : " + msg.arg1);
				break;
			case 1:
				mBackTv.setText("Root Result : " + ((Double)msg.obj).doubleValue());
				break;
			}
		};
	};
}


class CalcThread extends Thread {
	Handler mMainHandler;
	Handler mBackHandler;
	
	public CalcThread(Handler mMainHandler) {
		super();
		this.mMainHandler = mMainHandler;
	}
	
	@Override
	public void run() {
		super.run();
		Looper.prepare();
		mBackHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Message retMsg = Message.obtain();
				switch(msg.what){
				case 0:
					retMsg.what = 0;
					retMsg.arg1 = msg.arg1 * msg.arg1;
					break;
				case 1:
					retMsg.what = 1;
					retMsg.obj = new Double(Math.sqrt((double) msg.arg1));
					break;
				}
				
				mMainHandler.sendMessage(retMsg);
			}
		};
		
		Looper.loop();
	}
}